package lagou.mode3.mode4;

import java.io.*;
import java.util.concurrent.Callable;

public class CopyDirectory implements Callable {
    private String source;
    private String dest;

    public CopyDirectory(String source,String dest){
        this.source=source;
        this.dest=dest;
    }

    //实现拷贝目录的功能
    public static void copyDir(String oldpath,String newpath) throws IOException {
        File file = new File(oldpath);
        String[] name=file.list();
        if(!(new File(newpath).exists())){
            (new File(newpath)).mkdir();
        }
        for(String na:name){
            if((new File(oldpath+ File.separator +na)).isDirectory())
                copyDir(oldpath+ File.separator +na , newpath+ File.separator +na);
            if((new File(oldpath+ File.separator +na)).isFile())
                copyFile(oldpath+ File.separator +na , newpath+ File.separator +na);
        }

    }

    //实现拷贝文件的功能
    public static void copyFile(String oldpath,String newpath) throws IOException {
        FileInputStream fileInputStream = new FileInputStream(oldpath);
        FileOutputStream fileOutputStream = new FileOutputStream(newpath);
        byte[] bArr=new byte[1024];
        int res=0;
        while ((res=fileInputStream.read(bArr))!=-1){
            fileOutputStream.write(bArr,0,res);
        }
        fileInputStream.close();
        fileOutputStream.close();

    }

    @Override
    public Object call() throws Exception {
        String th=Thread.currentThread().getName();
        System.out.println(th+"正在拷贝...");
        copyDir(source,dest);
        System.out.println(th+"拷贝完成");
        return null;
    }
}
